package sii.commons;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Log {
    private BufferedWriter bw;
    @SuppressWarnings("rawtypes")
    private Class classObj;
    private static Log instance;
    private boolean suppressConsole = false;
    private String logpath = "log-";
    public void suppressConsole() {
	suppressConsole = true;
    }
    
    public void writeConsole(boolean writeconsole) {
	suppressConsole = !writeconsole;
    }

    private Log() {
	try{
	   init(); 
	}catch(Exception e){}
	
    }

    @SuppressWarnings("rawtypes")
    public Log(Class class1) throws IOException {
	classObj = class1;
	init();
    }

    public static Log getInstance() {
	if (instance == null) {
	    instance = new Log();
	}
	return instance;
    }

    private void init() throws IOException {
	if (bw == null)
	    bw = new BufferedWriter(new FileWriter(logpath + classObj.getName()+".log"));
    }

    public void info(Object s) throws IOException {
	init();
	String line = getTime() + "   \t"  + s
		+ "\t\t (" + classObj.getCanonicalName() + ")\n";
	bw.write(line);
	bw.flush();
	if (!suppressConsole)
	    System.out.print(line);

    }

    public void error(String s, Throwable e) {
	
	String line = getTime() + " " + classObj.getCanonicalName() + "\n" + s
		+ "\n" + e.getMessage() + "\n";
	try {
	    init();
	    bw.write(line);
	    bw.flush();
	} catch (Exception e2) {
	}
	if (!suppressConsole){
	    System.err.println(line);
	    e.printStackTrace();
	    System.err.println();
	}
	

    }

    private static String getTime() {
	DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SS");
	Date date = new Date();
	return dateFormat.format(date);
    }
}
